package com.example.jpetstoremanager.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.jpetstoremanager.entity.Account;
import com.example.jpetstoremanager.entity.Profile;
import com.example.jpetstoremanager.entity.User;
import com.example.jpetstoremanager.service.AccountService;
import com.example.jpetstoremanager.service.UserService;
import com.example.jpetstoremanager.service.impl.UserServiceImpl;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
public class SelfInfoController {


    @Autowired
    private UserService userService;

    @Autowired
    private AccountService accountService;


    //管理员登录
    @GetMapping("/loginForm")
    public String loginForm(){
        return "login";
    }

    @PostMapping("/login")
    public String login(HttpServletRequest request, @RequestParam("code") String code, @RequestParam("email") String email, @Validated @ModelAttribute User user, BindingResult bindingResult,
                        Model model, HttpSession session){
        System.out.println("用户名、密码和验证码为："+user.getUsername()+","+user.getPassword()+","+code);
        //登陆失败
        //1、用户名、密码输入格式不正确
//        System.out.println(bindingResult.getAllErrors());
        StringBuilder validationErrorMsg = new StringBuilder();
        if(bindingResult.hasErrors()){
            for (ObjectError error: bindingResult.getAllErrors()){
                validationErrorMsg.append(error.getDefaultMessage());
                validationErrorMsg.append(",");
            }
            model.addAttribute("loginMsg",validationErrorMsg.subSequence(0,validationErrorMsg.length()-1));
            return "login";
        }

        //2、验证码不正确
        /*
        if(checkCode.equals("")){
            model.addAttribute("loginMsg","验证码不正确");
            return "login";
        }*/


        session = request.getSession();
        String emailCode = (String) session.getAttribute("email_code");
        // 验证码比对
        if (!StringUtils.equals(code, emailCode)) {
            request.setAttribute("error", "验证码错误");
            model.addAttribute("loginMsg","验证码不正确");
            return "account/signon";
        }
        //3、数据库查询失败
        User loginUser = userService.findUserByUsername(user.getUsername());
        System.out.println(loginUser);
        if(loginUser==null){
            model.addAttribute("loginMsg","用户名不存在");
            return "login";
        }else if(!user.getPassword().equals(loginUser.getPassword())){
            model.addAttribute("loginMsg","密码不正确");
            return "login";
        }
        else{//4、登陆成功
            System.out.println("登陆成功......");
            Account account = accountService.getAccount(user.getUsername());
            //放入账户信息
            session.setAttribute("account",account);
            //放入登录账号信息
            session.setAttribute("loginUser",loginUser);
            return "redirect:/dashboard";
        }
    }

    @GetMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute("loginUser");
        session.removeAttribute("account");
        return "redirect:/loginForm";
    }

    @GetMapping("/registerForm")
    public String registerForm(){
        return "register";
    }

    @GetMapping("/selfInfo")
    public String selfInfo(HttpSession session){

        User loginUser = (User) session.getAttribute("loginUser");
//        System.out.println(loginUser);
        session.setAttribute("loginUser",loginUser);
//        session.setAttribute("message2","");
//        //调取该account的profile
//        QueryWrapper<Profile> profileQueryWrapper = new QueryWrapper<>();
//        profileQueryWrapper.eq("userid",loginUser.getUsername());
//        Profile loginUserProfile = profileMapper.selectOne(profileQueryWrapper);
//        account.initProfile(loginUserProfile);
//        //将该用户的喜好信息填入session
//        session.setAttribute("profile",loginUserProfile);
//        System.out.println("用户："+loginUser.getUsername()+" 进入个人账户页面，语言喜好为："+loginUserProfile.getLangpref());
//
//        //封装一下所有categories
//        List<Category> categoryList = categoryMapper.selectList(null);
//        session.setAttribute("categories",categoryList);

        return "selfInfo";
    }

    @PostMapping("/UserInfoUpdate")
    public String userInfoUpdate(HttpSession session,@RequestParam("username-input") String username,
                                 @RequestParam("password-input") String password,
                               @RequestParam("email-input") String email,@RequestParam("age-input") String age
                               ){
        User loginUser = (User) session.getAttribute("loginUser");

        User updateUser=new User();
        updateUser.setId(loginUser.getId());
        updateUser.setUsername(username);
        updateUser.setPassword(password);
        updateUser.setEmail(email);
        updateUser.setAge(Integer.parseInt(age));
        updateUser.setIsAdmin(1);
        userService.updateUserById(updateUser);
        session.setAttribute("loginUser",updateUser);
        System.out.println(loginUser);

        return "selfInfo";
    }
}
